<?php

class Activity_Model_Logger
{
	//TODO: listener
	//TODO: referer


	public static function push($subjectClass, $subjectId, $action, $objects = NULL)
	{
		if (empty($subjectClass)) {
			throw new Exception('Invalid subject class id name');
		}
		if (intval($subjectId) < 1) {
			throw new Exception('Invalid subject ID');
		}
		if (empty($action)) {
			throw new Exception('Empty action');
		}


		$table = Activity_Model_DbTable_Activity::getInstance();

        $dbData = array(
			'time' => time() - date('Z'),
			'action' => $action,
        );

		$insertId = $table->insert($dbData);
		if (intval($insertId) === 0) {
			throw new Exception('Query error');
		}

		$activityId = $table->getAdapter()->lastInsertId();


		$table = Activity_Model_DbTable_Object::getInstance();

		$dbData = array(
			'activity_id' => $activityId,
			'role' => 'subject',
			'object_class' => $subjectClass,
			'object_id' => $subjectId,
		);
		$insertId = $table->insert($dbData);

		if (is_array($objects)) {
			foreach ($objects as $obj) {
				if (($obj instanceof Euso_ObjectRef) === FALSE && is_array($obj) === FALSE) {
					throw new Exception('Invalid object');
				}
				if (is_array($obj)) {
					$dbData = array(
						'activity_id' => $activityId,
						'role' => $obj['role'],
						'object_class' => $obj['class'],
						'object_id' => $obj['id'],
					);
				} else {
					$dbData = array(
						'activity_id' => $activityId,
						'role' => 'object',
						'object_class' => $obj->getObjectClassIdName(),
						'object_id' => $obj->getObjectId(),
					);
				}
				$insertId = $table->insert($dbData);
			}
		}
	}
}
